<template>
  <div class="component-three">
    <div class="select-container">
      <select v-model="selectedCountry" @change="fetchData">
        <option v-for="country in countries" :key="country" :value="country">{{ country }}</option>
      </select>
      <select v-model="selectedSport" @change="fetchData">
        <option v-for="sport in sports" :key="sport" :value="sport">{{ sport }}</option>
      </select>
    </div>

    <!-- 散点图容器 -->
    <div id="scatter-plot" style="width: 100%; height: 400px;"></div>

    <!-- 相关性系数表格 -->
    <div class="correlation-table">
      <table>
        <thead>
          <tr>
            <th colspan="3">相关性系数</th>
          </tr>
          <tr>
            <th></th>
            <th>Height</th>
            <th>Weight</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, index) in correlationData" :key="index">
            <td>{{ Object.keys(row)[0] }}</td>
            <td>{{ row.Height.toFixed(4) }}</td>
            <td>{{ row.Weight.toFixed(4) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 男女身高体重变化折线图 -->
    <div id="trend-chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

const countries = ref([])
const sports = ref([])
const selectedCountry = ref('不选择')
const selectedSport = ref('不选择')
const correlationData = ref([])
let scatterChart = null
let trendChart = null

// 获取国家列表
const fetchCountries = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/select_list_region')
    if (response.data.success) {
      countries.value = response.data.data
    }
  } catch (error) {
    console.error('获取国家列表失败：', error)
  }
}

// 获取运动项目列表
const fetchSports = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/get_sport_list')
    if (response.data.success) {
      sports.value = response.data.data
    }
  } catch (error) {
    console.error('获取运动项目列表失败：', error)
  }
}

// 初始化散点图
const initScatterChart = () => {
  const chartDom = document.getElementById('scatter-plot')
  scatterChart = echarts.init(chartDom)
}

// 初始化趋势图
const initTrendChart = () => {
  const chartDom = document.getElementById('trend-chart')
  trendChart = echarts.init(chartDom)
}

// 更新散点图数据
const updateScatterChart = (data) => {
  const option = {
    title: {
      text: '运动员身高体重散点图'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return `体重：${params.value[0]}\n身高：${params.value[1]}`
      }
    },
    xAxis: {
      name: 'Weight',
      type: 'value'
    },
    yAxis: {
      name: 'Height',
      type: 'value'
    },
    series: [{
      type: 'scatter',
      data: data.map(point => [point.weights, point.heights]),
      itemStyle: {
        color: '#FFA500'
      }
    }]
  }
  scatterChart.setOption(option)
}

// 更新趋势图数据
const updateTrendChart = (data) => {
  const maleData = data.filter(item => item.Sex === 'M')
  const femaleData = data.filter(item => item.Sex === 'F')

  const option = {
    title: {
      text: '男女运动员身高体重变化趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['男性身高', '男性体重', '女性身高', '女性体重']
    },
    xAxis: {
      type: 'category',
      data: [...new Set(data.map(item => item.Year))].sort()
    },
    yAxis: [
      {
        name: '身高 (cm)',
        type: 'value',
        min: 150,
        max: 200,
        interval: 5
      },
      {
        name: '体重 (kg)',
        type: 'value',
        min: 50,
        max: 120,
        interval: 5
      }
    ],
    series: [
      {
        name: '男性身高',
        type: 'line',
        data: maleData.map(item => item.Height)
      },
      {
        name: '男性体重',
        type: 'line',
        yAxisIndex: 1,
        data: maleData.map(item => item.Weight)
      },
      {
        name: '女性身高',
        type: 'line',
        data: femaleData.map(item => item.Height)
      },
      {
        name: '女性体重',
        type: 'line',
        yAxisIndex: 1,
        data: femaleData.map(item => item.Weight)
      }
    ]
  }
  trendChart.setOption(option)
}

// 获取并更新图表数据
const fetchData = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/height_weight_correlation', {
      params: {
        country: selectedCountry.value,
        sport: selectedSport.value
      }
    })

    if (response.data.success) {
      const { data_points, height_weight_corr, grouped_data } = response.data.data
      updateScatterChart(data_points)
      correlationData.value = height_weight_corr
      updateTrendChart(grouped_data)
    }
  } catch (error) {
    console.error('获取数据失败：', error)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  scatterChart?.resize()
  trendChart?.resize()
}

onMounted(async () => {
  await Promise.all([fetchCountries(), fetchSports()])
  initScatterChart()
  initTrendChart()
  fetchData()
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.component-three {
  padding: 20px;
}

.select-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

select {
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  width: 200px;
}

.correlation-table {
  margin: 20px 0;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin: 20px 0;
}

th, td {
  border: 1px solid #dcdfe6;
  padding: 12px;
  text-align: center;
}

th {
  background-color: #f5f7fa;
}
</style>
